package server

import (
	"errors"
	"gorm.io/gorm"
	"onerk4/zg5yk/ordering/common/dao/mysql"
	"onerk4/zg5yk/ordering/common/model"
	"onerk4/zg5yk/ordering/common/pkg"
	"onerk4/zg5yk/ordering/common/proto/user"
)

func UserLogin(req *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	mobile, err := mysql.QueryUserInfoByMobile(req.Mobile)
	if err != nil {
		return nil, errors.New("查询失败")
	}

	if mobile.ID == 0 {
		return nil, errors.New("没有改用户")
	}

	if mobile.Password != req.Password {
		return nil, errors.New("密码错误")
	}

	claims := pkg.CustomClaims{ID: mobile.ID}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}

	return &user.UserLoginResponse{Success: token}, nil
}

func ReceiveCoupon(req *user.ReceiveCouponRequest) (*user.ReceiveCouponResponse, error) {
	coupon, err := mysql.QueryCoupon(req.CouponId)
	if err != nil {
		return nil, err
	}

	userCoupon, err := mysql.QueryUserCoupon(req.CouponId, req.UserId)
	if err != nil {
		return nil, err
	}

	if userCoupon.ID != 0 {
		return nil, errors.New("你已经领取过了")
	}

	u := model.UserCoupon{
		Model:            gorm.Model{},
		Uid:              int(req.UserId),
		CouponId:         int(req.CouponId),
		CouponName:       coupon.CouponName,
		CouponLimit:      coupon.CouponLimit,
		MinimumAvailable: coupon.MinimumAvailable,
		Status:           2,
	}
	err = mysql.ReceiveCoupon(&u)
	if err != nil {
		return nil, errors.New("领取失败")
	}

	return &user.ReceiveCouponResponse{Success: "领取成功"}, nil
}

func ShowCoupon(req *user.ShowCouponRequest) (*user.ShowCouponResponse, error) {
	list, err := mysql.QueryShowCouponList(req.UserId, req.Status)
	if err != nil {
		return nil, err
	}

	var item []*user.CouponItem

	for _, lists := range list {
		item = append(item, &user.CouponItem{
			Uid:              int64(lists.Uid),
			CouponId:         int64(lists.CouponId),
			CouponName:       lists.CouponName,
			CouponLimit:      float32(lists.CouponLimit),
			MinimumAvailable: float32(lists.MinimumAvailable),
			Status:           int64(lists.Status),
		})
	}

	return &user.ShowCouponResponse{List: item}, nil
}
